
// 手写reactive 实现A2 = A0+A1
let A0, A1, A2, observes;
let A2Dom = document.querySelector('#A2')

function A0Change(e) {
  A0.value = Number(e.target.value)
}

function A1Change(e) {
  A1.value = Number(e.target.value)
}


//作用update是A0,A1的订阅者
const update = () => {
  A2 = A0.value + A1.value
  A2Dom.innerText = A2
}




let viewEffect = () => {
  console.log('这里时副作用！！！！');
}//===副作用方法执行update

function setViewEffect(fn) {
  viewEffect = fn
  fn()
}

const targetMap = new WeakMap()//键值对的集合
const proxyMap = new WeakMap()

function reactive(obj) {
  const existingProxy = proxyMap.get(obj)
  console.log(222, existingProxy);
  // 已被代理过直接返回避免重复代理
  if (existingProxy) return existingProxy


  // 未被代理重新代理
  const proxy = new Proxy(obj, {
    get(target, key, receiver) {
      const res = Reflect.get(target, key, receiver)
      track(target, key)//追踪订阅者
      return res
    },
    set(target, key, value, receiver) {
      const res = Reflect.set(target, key, value, receiver)
      // update()//依赖改变时的副作用
      // viewEffect()
      trigger(target, key)
      return res
    }
  })

  proxyMap.set(obj, proxy)
  return proxy

}

// 追踪订阅者
function track(target, key) {
  let depsMap = targetMap.get(target)
  if (!depsMap) {
    targetMap.set(target, (depsMap = new Map()))
  }
  let dep = depsMap.get(key)
  if (!dep) {
    depsMap.set(key, (dep = new Set()))
  }
  dep.add(update)
  console.log(targetMap);
}

function trigger(target, key) {
  const depsMap = targetMap.get(target)
  if (!depsMap) return
  const effects = depsMap.get(key)
  effects.forEach(effect => effect())
}




A0 = reactive({ value: null })
A1 = reactive({ value: null })


